<!DOCTYPE html> 
<html> 
<head> 
    <title>Anymap</title> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <link rel="stylesheet" href="jquery.mobile/jquery.mobile.structure-1.3.1.min.css" />
    <link rel="stylesheet" href="jquery.mobile/jquery.mobile.theme-1.3.1.min.css" />
    <script src="jquery.mobile/jquery-1.9.1.min.js"></script>
    <script src="jquery.mobile/jquery.mobile-1.3.1.min.js"></script>
    <!-- load VsLib -->
    <script src="VsLib/xdr.js"></script>
    <script src="VsLib/VsLib.min.js"></script>
    <script src="VsServiceMethod.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;language=th"></script>
    <style>
       .page-map, .ui-content, #map-canvas { width: 100%; height: 100%; padding: 0; }
        #map-canvas { min-height: 100%; }
    </style>
    <script>
      var serviceMethod = new VsSeviceMethod();
      var NorthEast, SouthWest;
      var mCircle;
      var map;
      var markersArray = [];
      var userpos;
      var loadedJSONdata = [];
      var userGetPins = {
            "user_map_view":
                {
                    "center_latlng": { "lat": 18.28781494186995, "lng": 89.6748359068345 },
                    "bounds": { "sw": { "lat": 2.916747876840908, "lng": 52.98049996933461 }, "ne": { "lat": 32.413390076445864, "lng": 126.3691718443362 } },
                    "zoom_lv": 4, "time_period": { "start": "2013-01-23T08:06:41.386Z", "end": "2013-01-31T15:43:12.401Z" }
                },
            "user_authen": { "UserName": "anonymous", "UserId": "000", "key": "000" }
        };
      var infowindow = new google.maps.InfoWindow({
          maxWidth: 100
      });
      function initialize() {
        var mapOptions = {
          zoom: 8,
          center: new google.maps.LatLng(18.28781494186995, 89.6748359068345),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        var homeControlDiv = document.createElement('div');
        mylocation.MyLocationControl(homeControlDiv, map);
        homeControlDiv.index = 1;
        map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(homeControlDiv);
        // Try HTML5 geolocation
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            userpos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);  
            userGetPins.user_map_view.center_latlng.lat = position.coords.latitude;
            userGetPins.user_map_view.center_latlng.lng = position.coords.longitude;
            map.setCenter(userpos);
          }, function() {
            handleNoGeolocation(true);
          }); 
        } else {
          // Browser doesn't support Geolocation
          handleNoGeolocation(false);
        }
        google.maps.event.addListener(infowindow, 'closeclick', function() {
          // 3 seconds after the center of the map has changed, pan back to the
          // marker.
           $('#one_infopins').html('');
        });
        google.maps.event.addListener(map,'center_changed',function() {
          userpos = map.getCenter();
          var mapbb = map.getBounds();
          NorthEast = mapbb.getNorthEast(); 
          SouthWest = mapbb.getSouthWest();
          userGetPins.user_map_view.bounds.ne.lat = NorthEast.lat();
          userGetPins.user_map_view.bounds.ne.lng = NorthEast.lng();
          userGetPins.user_map_view.bounds.sw.lat = SouthWest.lat();
          userGetPins.user_map_view.bounds.sw.lng = SouthWest.lng();
          createServicePins();
        });
      }   
      function handleNoGeolocation(errorFlag) {
        if (errorFlag) {
          var content = 'Error: The Geolocation service failed.';
        } else {
          var content = 'Error: Your browser doesn\'t support geolocation.';
        }
      }
      function createServicePins() {
        serviceMethod.getPinId(userGetPins.user_map_view, userGetPins.user_authen, function (data) {
           // console.log( JSON.stringify(userGetPins));
            var num = 0;
            clearOverlays();
            serviceMethod.getPinByIds(data, userGetPins.user_authen, function (r) {
               loadedJSONdata = r;
               localStorage.infodata = JSON.stringify(r);
               for (var i = 0; i < r.length; i++) {                           
                    var d = r[i];
                    var _topic = typeof d['topic'] == "object" ? JSON.stringify(d['topic']) : d['topic'];
                    var _brief = typeof d['brief'] == "object" ? JSON.stringify(d['brief']) : d['brief'];
                    var _icon = typeof d['icon_url'] == "object" ? JSON.stringify(d['icon_url']) : d['icon_url'];
                    var _la_lng = d['la_lng'];
                    var markpos = new google.maps.LatLng(_la_lng.lat,_la_lng.lng);
                    markersArray[i] = new google.maps.Marker({
                        icon: "images/marker.png",
                        position: markpos,
                        map: map,
                        title:_topic
                    });
                    bindInfoWindow(markersArray[i], map, infowindow, _topic);
                }
            });
            /*
            var mCirCleOption = {
               strokeColor: '#FF0000',
               strokeOpacity: 0.2,
               strokeWeight: 1,
               fillColor: '#FF0000',
               fillOpacity: 0,
               map: map,
               bounds: map.getBounds()
          };
          mCircle = new google.maps.Rectangle(mCirCleOption);*/
        });
      }
      function bindInfoWindow(marker, map, infowindow, html) {
          google.maps.event.addListener(marker, 'click', function() {
              infowindow.setContent(html);
              infowindow.open(map, marker);
              $("#content_two").html(html);
              //$('#runningup').panel('open');
              $.mobile.changePage( "#runningup", { transition: "slideup"} );
          });
      } 
      function clearOverlays() {
        for (var i = 0; i < markersArray.length; i++ ) {
          markersArray[i].setMap(null);
        }
      }
      google.maps.event.addDomListener(window, 'load', initialize);
      $(document).on('pagebeforeshow', '#timeline', function(){       
          michaelajax.parseJSONP(loadedJSONdata, '#timelinelist');
      });
      $(document).on('pagebeforeshow', '#listviewitem', function(){       
          michaelajax.parseJSONP(loadedJSONdata, '#ilist');
      });
      $(document).on('pagebeforeshow', '#filteroptionview', function(){     
          contnormalize.loadString(localStorage.infodata);
          contnormalize.recompiling();
      });
      $(document).on('pageshow', '#filteroptionview', function(){   
        var deCont = [];
        $('input').click(function(data) {
          if(typeof(localStorage.FilterContent)==="string") {
            var h = localStorage.FilterContent;
            deCont = h.split(',');
          }
          if($(this).is(":checked")==false) {
            if(contnormalize.inArray($(this).attr('name'), deCont)===false) {
              deCont.push($(this).attr('name'));
            }
          }else{
            deCont = contnormalize.RemoveEle($(this).attr('name'), deCont); 
          }
          localStorage.FilterContent = deCont.join(",");
          console.log(deCont);
        });
      }); 
      $(document).on('pageshow', '#langview', function(){   
        /*for radio choice*/
        $('[name="radio-choice"]').click(function(data) {
          localStorage.setLang = $(this).val();
        });
      }); 
      $(document).on('pagebeforeshow', '#langview', function(){   
        /*for radio choice*/
        if(typeof(localStorage.setLang)!=="undefined") {
          $.each($('[name="radio-choice"]'), function(){
            if(localStorage.setLang==$(this).val()) {
              $(this).prop("checked",true).checkboxradio("refresh"); 
            }else{
              $(this).prop("checked",false).checkboxradio("refresh"); 
            }
          });
        }
      }); 
      $(document).on( "pageshow", '#mapview', function( event, data ) {
        if(data.prevPage.length>0) {
          google.maps.event.trigger(map, 'resize');
          map.setCenter(userpos);
        }
      });
      var michaelajax = {  
        jsonResult : null,
        parseJSONP:function(result, id){
            $(id).empty();
            $.each(result, function( index, value ) {
              var result = '<li><a href="#"><img src="'+value.icon_url+'" alt="" class="ui-li-icon">'+ value.topic +'</li>'; 
              $(id).append(result);
            });
            $(id).listview('refresh');
        }
      };
      var mylocation = {
        MyLocationControl:function (controlDiv, map) {
          // Set CSS styles for the DIV containing the control
          // Setting padding to 5 px will offset the control
          // from the edge of the map
          controlDiv.style.padding = '5px';

          // Set CSS for the control border
          var controlUI = document.createElement('div');
          controlUI.style.cursor = 'pointer';
          controlUI.style.textAlign = 'center';
          controlUI.title = 'Click to set the map to Your location';
          controlDiv.appendChild(controlUI);

          // Set CSS for the control interior
          var controlText = document.createElement('div');
          controlText.innerHTML = '<img src="images/ic_mylocationb.png"/>';
          controlUI.appendChild(controlText);

          // Setup the click event listeners: simply set the map to
          // Chicago
          google.maps.event.addDomListener(controlUI, 'click', function() {
           if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) { 
                    var userorigin = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);  
                    map.setCenter(userorigin);
                });    
            }else{
                alert("Please allow application to tracking your location ");
            }
          });
        }
      };
      var contnormalize = {
        jsonobject: null,
        RemoveEle:function(n, h) {
          var a = []
          $.each(h, function(i,d){
              if(n!==d) a.push(d);
          });
          return a;
        },
        ReArray:function(iArr) {
          var x = []
          $.each(iArr, function(index,data){
            if(data.length>0) x.push(data);
          });
          return x;
        },
        inArray:function(needle, haystack) {
        var boole = false;
            $.each(haystack, function(index,data){
                if(needle===data) boole = true;
            });
            return boole;
        },
        loadString:function(JSONString) {
            this.jsonobject = JSON.parse(JSONString);
        },
        recompiling:function() {
           if(this.jsonobject!==null) {
               var filterarr = [];
               var Storage = [];
               if(typeof(localStorage.FilterContent)!=="undefined") Storage = this.ReArray(localStorage.FilterContent.split(','));
               var iChk = "";
               $('.filterlist').empty();
               $.each(this.jsonobject, function(index,data){
                  if(typeof(data.usr_id)==="string") {
                      if(contnormalize.inArray(data.usr_id, filterarr)===false) {
                          filterarr.push(data.usr_id);
                      }
                  }
               });
               $.each(filterarr, function(index,data){
                iChk=(contnormalize.inArray(data,Storage))?"":'checked="checked"';
                var result = '<input type="checkbox" name="'+data+'" id="checkbox-'+data+'" class="custom" '+iChk+' /><label for="checkbox-'+data+'">'+data+'</label>';
                $('.filterlist').append(result);      
               });
               $("#filter-canvas").trigger ("create");
           } 
        }
      }
    </script>
</head> 
<body> 
<div data-role="page" id="mapview" class="page-map">
    <div data-role="header" id="header_one" data-fullscreen="true" data-position="fixed">
      <div data-role="navbar" data-theme="a">
          <ul>
              <li><a href="#" data-theme="a" class="ui-btn-active ui-state-persist">Map View</a></li>
              <li><a href="#timeline" data-theme="a" data-transition="none">Time Line</a></li>
              <li><a href="#listviewitem" data-theme="a">List</a></li>
              <li><a href="#filteroptionview" data-theme="a">Filter</a></li>
              <li><a href="#langview" data-theme="a">Language</a></li>
          </ul>
      </div>
    </div>
    <div data-role="content" id="mapcnv">
      <div id="map-canvas">
      </div>
    </div>
</div>
<div data-role="page" id="timeline" class="page-map">
  <div data-role="header" id="header_one"  data-position="fixed">
      <div data-role="navbar" data-theme="a">
          <ul>
              <li><a href="#mapview" data-theme="a">Map View</a></li>
              <li><a href="#" data-theme="a" class="ui-btn-active ui-state-persist">Time Line</a></li>
              <li><a href="#listviewitem" data-theme="a">List</a></li>
              <li><a href="#filteroptionview" data-theme="a">Filter</a></li>
              <li><a href="#langview" data-theme="a">Language</a></li>
          </ul>
      </div>
  </div>
  <div data-role="content">
      <ul data-role="listview" id="timelinelist" data-inset="true"></ul>
  </div>
  <div data-role="footer">
    <h6><a href="#" data-role="button" data-icon="plus" data-theme="a" data-inline="true">More ...</a></h6>
  </div>
</div>
<div data-role="page" id="listviewitem" class="page-map">
  <div data-role="header" id="header_one"  data-position="fixed">
      <div data-role="navbar" data-theme="a">
          <ul>
              <li><a href="#mapview" data-theme="a">Map View</a></li>
              <li><a href="#timeline" data-theme="a">Time Line</a></li>
              <li><a href="#" data-theme="a" class="ui-btn-active ui-state-persist">List</a></li>
              <li><a href="#filteroptionview" data-theme="a">Filter</a></li>
              <li><a href="#langview" data-theme="a">Language</a></li>
          </ul>
      </div>
  </div>
  <div data-role="content">
      <ul data-role="listview" id="ilist" data-inset="true"></ul>
  </div>
</div>
<div data-role="page" id="filteroptionview" class="page-map">
  <div data-role="header" id="header_one"  data-position="fixed">
      <div data-role="navbar" data-theme="a">
          <ul>
              <li><a href="#mapview" data-theme="a">Map View</a></li>
              <li><a href="#timeline" data-theme="a">Time Line</a></li>
              <li><a href="#listviewitem" data-theme="a">List</a></li>
              <li><a href="#" data-theme="a" class="ui-btn-active ui-state-persist">Filter</a></li>
              <li><a href="#langview" data-theme="a">Language</a></li>
          </ul>
      </div>
  </div>
  <div data-role="content">
      <div id="filter-canvas">
          <fieldset data-role="controlgroup">
            <legend>Content</legend>
            <div class="filterlist"></div>
          </fieldset>
      </div>
  </div>
</div>
<div data-role="page" id="langview" class="page-map">
  <div data-role="header" id="header_one"  data-position="fixed">
      <div data-role="navbar" data-theme="a">
          <ul>
              <li><a href="#mapview" data-theme="a">Map View</a></li>
              <li><a href="#timeline" data-theme="a">Time Line</a></li>
              <li><a href="#listviewitem" data-theme="a">List</a></li>
              <li><a href="#filteroptionview" data-theme="a">Filter</a></li>
              <li><a href="#" data-theme="a" class="ui-btn-active ui-state-persist">Language</a></li>
          </ul>
      </div>
  </div>
  <div data-role="content">
      <div id="lang-canvas">
      <fieldset data-role="controlgroup">
        <legend>Language</legend>
            <input type="radio" name="radio-choice" id="radio-choice-1" value="en" checked="checked" />
            <label for="radio-choice-1">English</label>
            <input type="radio" name="radio-choice" id="radio-choice-2" value="th"  />
            <label for="radio-choice-2">Thai</label>
            <input type="radio" name="radio-choice" id="radio-choice-3" value="jp"  />
            <label for="radio-choice-3">Japanese</label>
            <input type="radio" name="radio-choice" id="radio-choice-4" value="cn"  />
            <label for="radio-choice-4">Mandarin</label>
      </fieldset>
      </div>
  </div>
</div>
<div data-role="page" id="runningup" data-theme="a">
	<div data-role="header">
                        <h1>My App</h1>
	</div>
    <div id="content_two" data-role="content" data-theme="a">	
	</div>
	<div data-role="footer">
		<h4><a href="#mapview" data-role="button" data-icon="home" data-theme="a" data-inline="true">Back to page "Maps View"</a></h4>
	</div>
</div>
</body>
</html>